package com.octopus.kernal.service;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.jbpm.api.Execution;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;
import org.springframework.stereotype.Service;

@Service
public class WorkflowService {
	
	@Resource
	private ProcessEngine processEngine;
	
	public List<ProcessInstance> getAllProcesses(){
		ExecutionService executionService = processEngine.getExecutionService();
		List<ProcessInstance> list = executionService.createProcessInstanceQuery().list();
		return list;
	}
	
	public String deploy(String processFileName){
		String deploymentId = processEngine.getRepositoryService().createDeployment().addResourceFromClasspath(processFileName).deploy();
		return deploymentId;
	}
	
	public String start(String processName){
		ExecutionService executionService = processEngine.getExecutionService();
		ProcessInstance processInstance = executionService.startProcessInstanceByKey(processName);
		return processInstance.getId();
	}
	
	public void signal(String processId, String step, Map<String, ?> map){
		ExecutionService executionService = processEngine.getExecutionService();
		ProcessInstance processInstance = executionService.findProcessInstanceById(processId);
		Execution exec = processInstance.findActiveExecutionIn(step);
		executionService.signalExecutionById(exec.getId(), map);
	}
	
	public Set<String> findActiveActivityNames(String processInstanceId){
		ExecutionService executionService = processEngine.getExecutionService();
		Execution execution = executionService.findExecutionById(processInstanceId);
		return execution.findActiveActivityNames();
	}
	
	public void delete(String processId){
		ExecutionService executionService = processEngine.getExecutionService();
		executionService.deleteProcessInstance(processId);
	}

}
